package com.servertrack;
import java.util.List;
import org.springframework.context.MessageSource

import com.commonProject.common.intefaces.IHotel;
import com.commonProject.common.classes.HotelDTO;
import com.commonProject.common.exception.ValidateException

class HotelService implements IHotel{
	static transactional = true
	MessageSource messageSource
	
	List<HotelDTO> getlist(Long hotel_id){
		List<HotelDTO> dtoList=new ArrayList<HotelDTO>()
		
		Tur turTo=Tur.get(hotel_id)
	
		HotelDTO dto=null
		
		List<Hotel>hotel=Hotel.findAllByTur(turTo)		  
		hotel.each{
			dto=new HotelDTO()
			dto.title = it.title
			dto.id  = ("Hotel_"+it.id)	
			dtoList<<dto
		}
		 
	
		return 	dtoList			
	}
	
	
	HotelDTO getelement(Long hotel_id){
		HotelDTO dto=new HotelDTO()
	  	
		def el = Hotel.get(hotel_id)
		dto.id=el.id;
		dto.title=el.title;
		dto.adress=el.adress;
		dto.website=el.website;
		dto.description=el.description;
		dto.dateCreated=el.dateCreated;
		
		return dto;
	}
	
	HotelDTO deleteElement(Long hotel_id){
		def el=Hotel.get(hotel_id)
		el.delete()
	}
	
	public void addElement(Long hotel_id,String hotel_title,String hotel_adress,String hotel_website,String hotel_description) throws ValidateException{
		Tur tur=Tur.get(hotel_id)
		println("tur"+tur)
		println("Add Hotel SERVER"+tur)		
		if (tur) {
			Hotel newhotel=new Hotel()
			newhotel.title=hotel_title
			newhotel.adress=hotel_adress
			newhotel.website=hotel_website
			newhotel.description=hotel_description
			newhotel.dateCreated=new Date()
			newhotel.tur=tur
			
			if (!newhotel.save()){			
				def err = newhotel.errors.allErrors.collect{[
					errorMessage:messageSource.getMessage(it, null)			
				]}
				throw new ValidateException(err)				
			}			
		}
	}
	
	public void editElement(Long hotel_id,String h_title,String h_adress,String h_website,String h_description,String h_dateCreated) throws  ValidateException{
		println("Edit Hotel SERVER")
		def hotel=Hotel.get(hotel_id)
		hotel.title=h_title
		hotel.adress=h_adress
		hotel.website=h_website
		hotel.description=h_description
		if (h_dateCreated){
			hotel.dateCreated = new Date(h_dateCreated)
		}else{
			hotel.dateCreated = null
		}
					
		if (!hotel.save()){			
				def err = hotel.errors.allErrors.collect{[
					errorMessage:messageSource.getMessage(it, null)			
				]}
				throw new ValidateException(err)				
			}
	}	
}
